let express = require('express');
let router = express.Router();
let filter = require('../../components/filter');

// 科目每层id的长度
let SubjectIdLength = 3;
// 数据权限层级
let dataLevel = 1;

router.get('/data', filter.authorize, function (req, res, next) {
    if (global.trees.length === 0) {
        req.app.db.query("SELECT id, title as text, SUBSTRING(id, 1, types * " + SubjectIdLength + ") as parentId, types from subject", [], function (err, results, fields) {
            if (err) {
                res.json({"success": false, "message": global.databaseErr, "detail": err});
                return;
            }

            for (var i = 0; i < results.length; i ++) {
                if (results[i].parentId === "") {
                    global.trees.push(results[i]);
                }
                else {
                    makeTree(global.trees, results[i]);
                }
            }

            checkTree(req, res);
        });
    }
    else {
        checkTree(req, res);
    }
});

/**
 * 获取科目树 by v 2018-07-05
 *
 *
 */
router.get('/subject', filter.authorize, function (req, res, next) {
    let params = req.query;

    var sql = "";
    var datas = [];

    if (params.types >= 0) {
        sql = " where types <= ?";
        datas.push(params.types);
    }

    if (global.trees.length === 0) {
        req.app.db.query("SELECT id, title as text, SUBSTRING(id, 1, types * " + SubjectIdLength + ") as parentId, types from subject", [], function (err, results, fields) {
            if (err) {
                res.json({"success": false, "message": global.databaseErr, "detail": err});
                return;
            }

            for (var i = 0; i < results.length; i ++) {
                if (results[i].parentId === "") {
                    global.trees.push(results[i]);
                }
                else {
                    makeTree(global.trees, results[i]);
                }
            }

            filterTree(req, res);
        });
    }
    else {
        filterTree(req, res);
    }
});

function makeTree(r, data) {
    if (r !== undefined) {
        for (var i = 0; i < r.length; i ++) {
            if (data.parentId.indexOf(r[i].id) === 0) {
                if (r[i].id === data.parentId) {
                    if (r[i].nodes === undefined) {
                        r[i].nodes = [];
                    }
                    r[i].nodes.push(data);
                }
                else {
                    makeTree(r[i].nodes, data);
                }
            }
        }
    }
}

function checkTree(req, res) {
    let params = req.query;
    var datas = JSON.parse(JSON.stringify(global.trees));

    cutTreeByTypes(datas, 1);
    checkTreeByRole(datas, params.subjectIds === undefined ? "" : params.subjectIds);

    res.json({"success": true, "data": datas, "message": ""});
}

function filterTree(req, res) {
    var datas = JSON.parse(JSON.stringify(global.trees));

    let params = req.query;
    if (params.types >= 0) {
        cutTreeByTypes(datas, params.types);
    }

    let role = req.session.role;
    let user = req.session.user;
    if (role.id !== 1) {
        cutTreeByRole(datas, user.subjectIds);
    }

    res.json({"success": true, "data": datas, "message": ""});
}

/**
 * 根据types剪裁树 by v 2018-07-05
 *
 * @param datas
 * @param types
 */
function cutTreeByTypes(datas, types) {
    if (datas !== undefined && datas.length > 0) {
        for (var i = 0; i < datas.length; i ++) {
            if (datas[i].types == types) {
                datas[i].nodes = undefined;
            }
            else {
                cutTreeByTypes(datas[i].nodes, types);
            }

        }
    }
}

/**
 * 根据数据权限剪裁树 by v 2018-07-05
 *
 * @param datas
 * @param subjectIds
 */
function cutTreeByRole(datas, subjectIds) {
    if (datas !== undefined && datas.length > 0) {
        for (var i = 0; i < datas.length; i ++) {
            if (datas[i].types <= dataLevel) {
                if (subjectIds.indexOf("," + datas[i].id + ",") === -1) {
                    datas.splice(i, 1);
                    i --;
                }
                else {
                    if (datas[i].types < dataLevel) {
                        cutTreeByRole(datas[i].nodes, subjectIds);
                    }
                }
            }
        }
    }
}

/**
 * 根据数据权限添加复选框 by v 2018-07-05
 *
 * @param datas
 * @param subjectIds
 */
function checkTreeByRole(datas, subjectIds) {
    if (datas !== undefined && datas.length > 0) {
        for (var i = 0; i < datas.length; i ++) {
            if (subjectIds.indexOf("," + datas[i].id + ",") >= 0) {
                datas[i].state = {"checked": true};
            }

            if (datas[i].nodes !== undefined && datas[i].nodes.length > 0) {
                checkTreeByRole(datas[i].nodes, subjectIds);
            }
        }
    }
}

module.exports = router;